package com.zwim.core;

import com.zwim.core.handle.ServerChannelHandlerAdapter;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;
import javax.annotation.Resource;

@Component
@Slf4j
public class NettyServerListener {
    @Autowired
    ServerBootstrap bootstrap;
    @Autowired
    @Qualifier("nioEventLoopGroup")
    EventLoopGroup boss;
    @Autowired
    @Qualifier("nioEventLoopGroup")
    EventLoopGroup work;
    @Resource
    ServerChannelHandlerAdapter channelHandlerAdapter;
    @Value("netty.port")
    int nettyPort;
    @Value("netty.loglevel")
    String logLevel;
    @PreDestroy
    public void colse(){
        boss.shutdownGracefully();
        work.shutdownGracefully();
    }

    public void start(){
        bootstrap.group(boss,work)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG,100)
                .handler(new LoggingHandler(logLevel));
        bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
           @Override
            protected  void initChannel(SocketChannel ch){
               ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(65535
                       , 0, 2, 0, 2))
                       .addLast(new LengthFieldPrepender(2))
                      // .addLast(new ObjectCodec())
                       .addLast(channelHandlerAdapter);

           }
        });



    }




}
